from fdfs_client.client import Fdfs_client
from rest_framework import serializers

from apps.goods.models import Brand
from meiduo_mall import settings


class BrandSerializer(serializers.ModelSerializer):
    '''
        商品类别序列化器
    '''
    class Meta:
        model = Brand
        fields = '__all__'

    # 重写create方法, 把图片上传到fastDFS中
    def create(self, validated_data):
        # 1. 建立fastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 2. 获取图片数据 在序列化器中获取request
        request = self.context['request']
        image_file = request.data.get('logo')
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')
        # 3. 上传图片
        ret = client.upload_by_buffer(image_file.read())
        # 4. 判断返回结果
        if ret['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        # 5. 上传成功将返回的文件路径保存到品牌表中
        image_url = ret['Remote file_id']
        img = Brand.objects.create(logo=image_url, name=name, first_letter=first_letter)
        # 6. 返回保存后的图片对象数据
        return img

    def update(self, instance, validated_data):
        # 1. 建立fastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 2. 获取图片数据 在序列化器中获取request
        request = self.context['request']
        image_file = request.data.get('logo')
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')
        # 3. 上传图片
        ret = client.upload_by_buffer(image_file.read())
        # 4. 判断返回结果
        if ret['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        # 5. 上传成功将返回的文件路径更新到图片表中
        image_url = ret['Remote file_id']
        instance.logo = image_url
        instance.name = name
        instance.first_letter = first_letter
        instance.save()
        # 6. 返回保存后的图片对象数据
        return instance